import crossBlue from '@/image/cross_blue.png'
import crossRed from '@/image/cross_red.png'
import { generateId } from './utils'

export class NetLink {
  constructor(map, startUnit, endUnit) {
    this.color = startUnit.type === 0 ? '#FF0033' : '#99CCFF'
    this.map = map
    this.runingTime = 0
    this.visible = true
    this.start = startUnit.coor
    this.end = endUnit.coor
    this.path = this.generateCoors(this.start, this.end)
    this.lineLayer = new BMapGL.Polyline(this.path, {
      strokeWeight: 2,
      strokeStyle: 'solid',
      strokeColor: this.color,
    })
    this.map.addOverlay(this.lineLayer)
    this.type = startUnit.type
    this.id = generateId(startUnit.label, endUnit.label)

  }
  generateCoors(start, end) {
    this.midCoor = [(start[0] + end[0]) / 2, (start[1] + end[1]) / 2]
    return [new BMapGL.Point(...start), new BMapGL.Point(...end)]
  }
  updateFeature(coor, type) {
    if (!type) {
      this.start = coor
    } else {
      this.end = coor
    }
    this.path = this.generateCoors(this.start, this.end)
    this.lineLayer.setPath(this.path)
  }
  removeSolid(time) {
    this.addCross()
    this.interval = setInterval(() => {
      this.animateAction(time)
    }, 400)
    this.animateAction(time)
  }
  addCross() {
    this.point = new BMapGL.Point(...this.midCoor)
    const icon = new BMapGL.Icon(this.type ? crossBlue : crossRed, new BMapGL.Size(24, 24))
    this.marker = new BMapGL.Marker(this.point, {
      size: 24,
      icon,
    })
    this.map.addOverlay(this.marker)
  }
  animateAction(time) {
    if (this.runingTime > time) {
      this.map.removeOverlay(this.marker)
      this.visible = true
      this.switchDashed()
      this.runingTime = 0
      clearInterval(this.interval)
      return
    }
    if (this.visible) {
      this.visible = !this.visible
      this.lineLayer.hide()
      this.marker.hide()
    } else {
      this.visible = !this.visible
      this.lineLayer.show()
      this.marker.show()
    }
    this.runingTime += 100
  }
  switchDashed() {
    this.lineLayer.setStrokeStyle('dashed')
    this.lineLayer.show()
  }
  hide() {
    this.lineLayer.hide()
  }
  show() {
    this.lineLayer.show()
  }
  destroy() {
    this.map.removeOverlay(this.lineLayer)
    Object.keys(this).forEach(key => {
      delete this[key]
    })
    this.destroyed = true
  }
}
